package com.xinyue.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDao {
	//实现增删改查的功能  以及连接 和释放资源
		Connection cnt=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		
		//连接有3种方式
		public boolean getConnection(){//连接数据库
			String driver="com.mysql.jdbc.Driver";
			String url="jdbc:mysql://localhost:3306/xinyue";
			String username="root";
			String password="0318";
			try {
				Class.forName(driver);
				cnt=DriverManager.getConnection(url,username,password);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return true;
			
		}
		
		//关闭资源
		public boolean closeResource(){
			if(rs!=null){
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			if(ps!=null){
				try {
					ps.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			if(cnt!=null){
				try {
					cnt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return true;
			
		}
		
		//增删改
		public int executeUpdate(String sql ,Object [] params){
			int updateRows=0;
			if(this.getConnection()){
				//获得sql语句
				try {
					ps=cnt.prepareStatement(sql);
					//给占位符的赋值
					for(int i=0;i<params.length;i++){
						ps.setObject(i+1,params[i] );
					}
					//执行 增删改,返回影响的行数
					updateRows=ps.executeUpdate();
					
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			return updateRows;
			
		}
	 
		//查询 全部信息 或者指定部分信息
		public ResultSet ExecuteQuery(String sql ,Object [] params){
			if(this.getConnection()){
				try {
					ps=cnt.prepareStatement(sql);
					//给占位符赋值
					for(int i=0;i<params.length;i++){
						ps.setObject(i+1, params[i]);
					}
					// 执行查询，返回值是ResultSet型的
					rs=ps.executeQuery();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return rs;
		}
		public int lengthrow(String sql) {
			int updateRows=0;
			if(this.getConnection()){
				//获得sql语句
				try {
					ps = cnt.prepareStatement(sql);
					System.out.println("success");
					rs = ps.executeQuery(sql);
					rs.last();
					updateRows = rs.getRow();
					
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			return updateRows;
		}
}
